import React, { useEffect, FC, useState } from 'react';
import { connect, ConnectProps, Loading, ConnectRC } from 'umi';
import _ from 'lodash';
import { Radio, Checkbox, Tooltip } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { getAttachmentContent } from '@/services/gis';
import IconFont from '@/components/IconFont';
import styles from './index.less';

import TreeContent from './TreeContent';

import useKml from './kml';

// 这个应该从module导入
interface DashboardState {
  projectId: string;
}

interface TreeProps extends ConnectProps {
  loading: boolean;
  collapsed: boolean;
  change: (collapsed: boolean) => void;
  projectId: string;
  isBlank: boolean;
}

type selectTreeType = 'model' | 'project';

const Tree: FC<TreeProps> = ({ collapsed, change, projectId, loading, dispatch, isBlank }) => {
  /** 项目/模型树 显示/隐藏 */
  const [treeVisible, setTreeVisible] = useState<boolean>(false);

  /** 项目/模型树 Tabs选中项 */
  const [selectTree, setSelect] = useState<selectTreeType>('project');

  /** 项目树 */
  const [projectTree, setProjectTree] = useState<any[]>([]);

  /** 项目树 - 选中项 */
  const [projectSelectKey, setProjectSelectKey] = useState<(string | number)[]>([]);

  /** 项目树 - 勾中项 */
  const [projectCheckedKey, setProjectCheckedKey] = useState<(string | number)[]>([]);

  /** 模型树 */
  const [modelTree, setModelTree] = useState<any[]>([]);

  /** 模型树 选中项 */
  const [modelSelectKey, setModelSelectKey] = useState<(string | number)[]>([]);

  /** 模型树 选中项 */
  const [modelCheckedKey, setModelCheckedKey] = useState<(string | number)[]>([]);

  /** kml列表 */
  const {
    setKmlList,
    // 风场范围
    FcKmlVisible,
    setFcKmlVisible,
  } = useKml();

  /** gltf列表 */
  const [GltfList, setGltf] = useState<any[]>([]);

  /** 3dtile列表 */

  /** kml - 风场 */
  // 显示 / 隐藏 / 移除 / 添加 / 批量移除 / 批量添加
  // const [] = useFcKml();

  /** kml - 道路 */
  // const [] = useDlKml();

  /** kml - 线缆/电缆 */
  // const [] = useXlKml();

  /** gltf - 风机 */

  /** gltf - 箱变 */

  /** 3dtil - 模型 */

  useEffect(() => {
    // 清空已加载的3dtil 模型
    // 清空已加载的kml 道路 风场 电缆/线缆
    // 清空已加载的gltf 风机 箱变

    // 获取风机，升压站坐标。 kml列表（道路和风场）
    handleQueryListByShortName(projectId);

    getProjectTree();
  }, [projectId]);

  const getProjectTree = () => {
    if (dispatch)
      dispatch({
        type: 'gis/getProjectTree',
        callback: (data: React.SetStateAction<any[]>) => {
          setProjectTree(data);
        },
      });
  };

  /** 获取项目结构树 */
  const handleQueryListByShortName = (projectShortname: string) => {
    const payload: {
      projectShortname?: string;
    } = {};
    if (projectShortname) {
      payload.projectShortname = projectShortname;
    }
    if (dispatch)
      dispatch({
        type: 'gis/getlistByShortName',
        payload,
        callback: async (res) => {
          console.log(res);
          const code = _.get(res, 'code', '0');
          const coordinateInfo = _.get(res, 'data.coordinateInfo', []) || [];
          const kmlInfo = _.get(res, 'data.kmlInfo', []) || [];
          if (code === '1') {
            console.log({ kmlInfo, coordinateInfo });
            /** kmlInfo kml列表（道路和风场） */
            const KMLList: any[] = [];
            if (Array.isArray(kmlInfo) && kmlInfo.length) {
              await kmlInfo.reduce(async (_, info) => {
                await _;
                // 附件。
                const url = await getDownloadAttachmentId(info.attachmentId);
                KMLList.push({ url, id: info.projectGuid, ...info });
              }, undefined);
              console.log(KMLList);
              setKmlList(KMLList);
            }
          }
        },
      });
  };

  const getDownloadAttachmentId = (attachmentId: string) =>
    new Promise((resolve, reject) => {
      getAttachmentContent(attachmentId).then((res) => {
        const { code = '0', data = [] } = res;
        // console.log('getDownloadAttachmentId：', attachmentId, res);
        if (code === '1' && data.length > 0) {
          const { id = '' } = data[0];
          if (id) {
            const url = `/xbybs/attachment/downloadAttachment/${id}`;
            resolve(url);
          } else {
            resolve('');
          }
        } else {
          resolve('');
        }
      });
    });

  console.log({ loading, dispatch });

  return treeVisible ? (
    <div className={styles.tree}>
      <div className={styles.head}>
        <Radio.Group
          size="small"
          value={selectTree}
          onChange={({ target }) => setSelect(target.value)}
        >
          <Radio.Button value="project">项目树</Radio.Button>
          <Radio.Button value="model">模型树</Radio.Button>
        </Radio.Group>
        <Checkbox checked={FcKmlVisible} onChange={({ target }) => setFcKmlVisible(target.checked)}>
          风场范围
        </Checkbox>
        <CloseOutlined className={styles.close} onClick={() => setTreeVisible(false)} />
      </div>

      <div className={styles.content}>
        <TreeContent
          projectTree={projectTree}
          projectSelectKey={projectSelectKey}
          setProjectSelectKey={setProjectSelectKey}
          projectCheckedKey={projectCheckedKey}
          setProjectCheckedKey={setProjectCheckedKey}
          type={selectTree}
          isBlank={isBlank}
          loading={loading}
        />
      </div>
    </div>
  ) : (
    <Tooltip placement="bottomLeft" title="隐藏/显示结构树">
      <div className={styles.toggleTree} onClick={() => setTreeVisible(true)}>
        <IconFont className={styles.icon} type="iconfile-tree" />
      </div>
    </Tooltip>
  );
};

export default connect(({ gis, loading }: { gis: DashboardState; loading: Loading }) => ({
  projectId: gis.projectId,
  loading: loading.models.gis,
}))(Tree);
